﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NoteList.Delegates;
using NoteList.EvtArgs;
using NoteList.Models;
using NoteList.Biz;

namespace NoteList.Forms
{
    public partial class MainForm : Form
    {
        private ZNotes _notes = null;
        private ZNoteProvider _provider = null;
        private ZNoteAlarmProvider _alarmProvider = null;
        private EditForm _editForm = null;
        private bool _needCloseToTaskBar = true;

        private EditForm CurrEditForm
        {
            get
            {
                if (_editForm == null)
                {
                    _editForm = new EditForm();
                    _editForm.OnNoteChanged += new NoteChanged(_editForm_OnNoteChanged);
                }
                return _editForm;
            }
        }

        public MainForm()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.iconotelist;
            NoteNotify.Icon = Properties.Resources.iconotelist;
            gvTasks.AutoGenerateColumns = false;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            _provider = new ZNoteProvider();
            _provider.OnNoteSaveCompleted += new NoteSaveCompleted(_provider_OnNoteSaveCompleted);
            _provider.OnNoteLoadCompleted += new NoteLoadCompleted(_provider_OnNoteLoadCompleted);

            LoadNotes();
        }

        private void LoadNotes()
        {
            _provider.AsynLoadNotes();
        }

        void _provider_OnNoteLoadCompleted(object sender, NotesEventArgs e)
        {
            _notes = e.Notes;
            BindNotes(_notes);
            _alarmProvider = ZNoteAlarmProvider.GetInstance(_notes);
            _alarmProvider.StartTimer();
            _alarmProvider.OnNoteTime += new NoteTimeCame(_alarmProvider_OnNoteTime);
        }

        delegate void BindNoteTable(ZNotes notes);
        private void BindNotes(ZNotes notes)
        {
            if (this.gvTasks.InvokeRequired)
            {
                BindNoteTable b = new BindNoteTable(BindNotes);
                this.Invoke(b, notes);
            }
            else
            {
                gvTasks.DataSource = new BindingList<ZNote>(notes);
            }
        }

        private void TaskNewTaskMenu_Click(object sender, EventArgs e)
        {
            CreateNewNote();
        }

        private void CreateNewNote()
        {
            CurrEditForm.ShowForm(this, null);
        }

        void _editForm_OnNoteChanged(object sender, NoteChangeEventArgs e)
        {
            if (e.IsNewNote)
            {
                _notes.Add(e.Note);
            }
            SaveUserNotes();
        }

        private void SaveUserNotes()
        {
            _provider.AnsySaveNotes(_notes);
        }

        void _provider_OnNoteSaveCompleted(object sender, NoteSaveEventArgs e)
        {
            System.Diagnostics.Trace.WriteLine("保存成功");
            BindNotes(_notes);
        }

        void _alarmProvider_OnNoteTime(object sender, NotesEventArgs e)
        {
            foreach (ZNote note in e.Notes)
            {
                ShowAlarm(note, true);
            }
        }

        private void TaskMenu_DropDownOpening(object sender, EventArgs e)
        {
            TaskEditTaskMenu.Enabled = TaskDeleteTaskMenu.Enabled = (gvTasks.SelectedCells.Count > 0);
        }

        private void TaskEditTaskMenu_Click(object sender, EventArgs e)
        {
            EditSelectedNote();
        }

        private void EditSelectedNote()
        {
            if (gvTasks.SelectedRows.Count > 0)
            {
                ZNote note = (ZNote)gvTasks.SelectedRows[0].DataBoundItem;
                CurrEditForm.ShowForm(this, note);
            }
        }

        private void gvTasks_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
        {
            if (e.RowIndex >= 0 && !gvTasks.Rows[e.RowIndex].Selected)
            {
                foreach (DataGridViewRow dgvr in gvTasks.SelectedRows)
                {
                    dgvr.Selected = false;
                }
                gvTasks.Rows[e.RowIndex].Selected = true;
            }
        }

        private void tlcmEdit_Click(object sender, EventArgs e)
        {
            EditSelectedNote();
        }

        private void tlcmNew_Click(object sender, EventArgs e)
        {
            CreateNewNote();
        }

        private void TaskDeleteTaskMenu_Click(object sender, EventArgs e)
        {
            DeleteSelectedTasks();
        }

        private void DeleteSelectedTasks()
        {
            DialogResult dr = MessageBox.Show("将删除所有选中的任务", "删除确认", MessageBoxButtons.OKCancel);

            if (dr == DialogResult.OK)
            {
                foreach (DataGridViewRow dgvr in gvTasks.SelectedRows)
                {
                    gvTasks.Rows.Remove(dgvr);
                    _notes.Remove((ZNote)dgvr.DataBoundItem);
                }
                SaveUserNotes();
            }
        }

        private void tlcmDelete_Click(object sender, EventArgs e)
        {
            DeleteSelectedTasks();
        }

        private void gvTasks_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            ZNote note = null;
            foreach (DataGridViewRow dgvr in gvTasks.Rows)
            {
                note = (ZNote)dgvr.DataBoundItem;
                ((DataGridViewImageCell)dgvr.Cells["ColAlarm"]).Value = (note.EnableAlarm) ? Properties.Resources.icoalarm : Properties.Resources.icoblank;
                DataGridViewImageCell dgvic = (DataGridViewImageCell)dgvr.Cells["ColTimeState"];
                if (note.AlarmTime == DateTime.MinValue)
                    dgvic.Value = Properties.Resources.icoblank;
                else if (note.AlarmTime.Date < DateTime.Today)
                {
                    dgvic.Value = Properties.Resources.icoredball;
                    dgvic.ToolTipText = "已过期";
                }
                else if (note.AlarmTime.Date == DateTime.Today)
                {
                    dgvic.Value = Properties.Resources.icoyellowball;
                    dgvic.ToolTipText = "今天过期的任务";
                }
                else
                {
                    dgvic.Value = Properties.Resources.icogreenball;
                    dgvic.ToolTipText = "未过期";
                }
            }
        }

        private void TaskExitMenu_Click(object sender, EventArgs e)
        {
            RealClose();
        }

        private void RealClose()
        {
            _needCloseToTaskBar = false;
            this.Close();
        }

        private void taskListContextMenu_Opening(object sender, CancelEventArgs e)
        {
            tlcmEdit.Enabled = tlcmDelete.Enabled = tlcmExpire.Enabled = (gvTasks.SelectedRows.Count > 0);
        }

        private void ttsNewTask_Click(object sender, EventArgs e)
        {
            CreateNewNote();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_needCloseToTaskBar)
            {
                e.Cancel = true;
                this.WindowState = FormWindowState.Minimized;
                this.ShowInTaskbar = false;
            }
        }

        private void ShowFormFromTaskBar()
        {
            this.ShowInTaskbar = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void NoteNotify_DoubleClick(object sender, EventArgs e)
        {
            ShowFormFromTaskBar();
        }

        private void ncmShowMainForm_Click(object sender, EventArgs e)
        {
            ShowFormFromTaskBar();
        }

        private void ncmNewTask_Click(object sender, EventArgs e)
        {
            CreateNewNote();
        }

        private void ncmExit_Click(object sender, EventArgs e)
        {
            RealClose();
        }

        private void gvTasks_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                EditSelectedNote();
            }
        }

        private void ViewViewEffect_Click(object sender, EventArgs e)
        {
            ShowAlarm(null);
        }

        public delegate void ShowAlarmHandler(ZNote note);
        public void ShowAlarm(ZNote note, bool ansy)
        {
            if (ansy)
                this.Invoke(new ShowAlarmHandler(ShowAlarm), note);
            else
                ShowAlarm(note);
        }


        private void ShowAlarm(ZNote note)
        {
            NoticeForm nf = new NoticeForm();
            nf.OnNoteChanged += new NoteChanged(nf_OnNoteChanged);
            nf.OnNoteEditRequest += new NodeEventHandler(nf_OnNoteEditRequest);
            nf.ShowNote(note);
        }

        void nf_OnNoteChanged(object sender, NoteChangeEventArgs e)
        {
            SaveUserNotes();
        }

        void nf_OnNoteEditRequest(object sender, NoteEventArgs e)
        {
            CurrEditForm.ShowForm(this, e.Note);
        }
    }
}
